package app.pages;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;

import app.dao.MemberDao;

import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.TextField;
import com.vaadin.ui.Window;

@Configurable(preConstruction = true)
public class LoginWindow extends Window{

	@Autowired MemberDao memberDao;

	private TextField usernameField;
	private TextField passwordField;
	
	LoginWindow(){
		
		//Style window
		setWidth("400px");
		setHeight("200px");
		setModal(true);
		
		// Fields needed for login
		usernameField = new TextField();
		passwordField = new TextField();
		
		// Adding components
		addComponent(usernameField);
		addComponent(passwordField);
		createLoginAndCancelButtons();
	}
	
	/** This method will create register and cancel buttons and validate the fields*/
	public void createLoginAndCancelButtons(){

		HorizontalLayout buttonsLayout = new HorizontalLayout();

		// Creating buttons
		Button registerButton = new Button("login",new ClickListener(){

			@Override public void buttonClick(ClickEvent event) {
				
				if(memberDao.getMemberByUsernameAndPassword(usernameField.getValue().toString(), 
						passwordField.getValue().toString()) != null){
					
					showNotification("You're successfully logged in");
				} else {
					showNotification("Error, incorrect username or password");
				}
			}
		});

		Button cancelButton = new Button("cancel",new ClickListener(){

			@Override public void buttonClick(ClickEvent event) {
				close();
			}
		});

		// Adding buttons to the layout
		buttonsLayout.addComponent(registerButton);
		buttonsLayout.addComponent(cancelButton);
		addComponent(buttonsLayout);
	}
}